package my.syncfilter;

import my.syncfilter.entity.BillConfig;
import my.syncfilter.entity.FileEntity;
import my.syncfilter.entity.MemoryDataStore;
import my.syncfilter.entity.MonitorData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public abstract class AbstractFileProcessor implements FileProcessor<FileEntity>{

    private static Logger logger = LoggerFactory.getLogger(AbstractFileProcessor.class);

    protected final MonitorData monitorData;
    protected final BillConfig billConfig;

    private AtomicBoolean parallel = new AtomicBoolean(false);

    //存放当前未处理的任务
    protected final ArrayBlockingQueue<FileEntity> processor;

    //记录下一步要做的工作
    protected FileProcessor nextFileProcessor;



    public AbstractFileProcessor(String prefix)
    {
        this.monitorData = MemoryDataStore.INSTANCE.getMonitorData(prefix);
        this.billConfig = MemoryDataStore.INSTANCE.getBillConfig(prefix);
        nextFileProcessor=null;
        processor = new ArrayBlockingQueue<>(2000);
    }

    public AbstractFileProcessor(String prefix,FileProcessor nextFileProcessor)
    {
        this.monitorData = MemoryDataStore.INSTANCE.getMonitorData(prefix);
        this.billConfig = MemoryDataStore.INSTANCE.getBillConfig(prefix);
        this.nextFileProcessor=nextFileProcessor;
        processor = new ArrayBlockingQueue<>(2000);
    }

    @Override
    public boolean submit(FileEntity t) {
        //此处只对任务进行保存，并不进行处理
        processor.add(t);
        return true;
    }

    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()){
            try {
                FileEntity take = processor.poll(1000, TimeUnit.MILLISECONDS);
                if(take == null) continue;
                if(ifExit(take)){
                    next(take);
                    return;
                }
                //处理数据
                if(process(take)){
                    next(take);
                }
                if(take.isEndFile()){
                    return;
                }
            } catch (Exception e) {
                logger.info("文件处理异常:",e);
            }
        }
    }

    public void next(Object o){
        if(nextFileProcessor!=null){
            //下一个处理
            nextFileProcessor.submit(o);
        }
    }

    @Override
    public boolean ifExit(FileEntity t) {
        if (monitorData.getStatus() == 4) {
            // 状态为4，直接停止
            return true;
        }
        return false;
    }

    @Override
    public boolean ifParallel() {
        return parallel.get();
    }

    @Override
    public void setParallel(boolean p) {
        parallel.set(p);
    }

}